# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
import time
from collections import OrderedDict
from typing import Any
from typing import List
from typing import Optional
from typing import Union

import numpy as np
import soundfile as sf
import yaml

import logging
logger = logging.getLogger('mylogger')
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
import librosa
from PIL import Image

import gradio as gr
print('gradio ver:{}'.format(gr.__version__))

import tempfile
from stylize_image import stylize_image
from stylize_video import stylize_video

styleDict = {'starrynight':['images/style_images/starry-night.jpg','models/starrynight.pth'],
             'mosaic':['images/style_images/mosaic.jpg','models/mosaic.pth'],
             'candy':['images/style_images/candy.jpg','models/candy.pth'],
            }

tmpdir = './tmp'
os.makedirs(tmpdir,exist_ok=True)
tmpImg = os.path.join(tmpdir,'tmp.jpg')
tmpVd = os.path.join(tmpdir,'tmp.mp4')

def style_builder(inputPath,style,styleImage):
    print(inputPath,style)
    modelPath = styleDict[style][1]
    print(modelPath)
    
    if inputPath.endswith('.jpg'):    
        stylize_image(inputPath,None,modelPath,tmpImg)
        return tmpImg
    elif inputPath.endswith('.mp4'):    
        stylize_video(inputPath,modelPath,tmpVd,1,None)
        return tmpVd
    else:
        return None


def onChangeStyle(style):
    print(style)
    imagePath = styleDict[style][0]
    image = Image.open(imagePath)
    return image
    

if __name__ == "__main__":
    
    
    # 定义输入和输出
    fileInput = gr.components.File(label="上传文件")
    outputs = gr.components.File(label="下载文件") 
    
    styleInput = gr.Dropdown(["starrynight", "mosaic", "candy"], label="Style", info="Will add more style later!")
    styleImage = gr.Image(show_label=False,interactive=False)
    inputs = [fileInput,styleInput,styleImage]
    
    
    app = gr.Interface(fn=style_builder, inputs=inputs, outputs=outputs,   title="文件上传、并生成可下载文件demo", description="上传任何文件都可以，只要大小别超过你电脑的内存即可")

    with app: 
        styleInput.change(onChangeStyle,inputs=[styleInput],outputs=[styleImage])
    
    

    app.launch(server_name='0.0.0.0',share=True)
    